//
//  UIImage+YFExtension.m
//  SquashSpark
//
//  Created by Coollang on 2017/11/3.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "UIImage+YFExtension.h"
#import <AVFoundation/AVFoundation.h>


@implementation UIImage (YFExtension)

+ (UIImage *)imageFromView:(UIView *)theView {
    if ([theView isKindOfClass:[UIScrollView class]]) {
        UIScrollView *scrollView = (UIScrollView *)theView;
        return [self imageFromView:theView atFrame:CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height)];
    }else {
        
        UIGraphicsBeginImageContextWithOptions(theView.frame.size, NO, 4.0f);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSaveGState(context);
        UIRectClip(CGRectMake(0, 0, theView.bounds.size.width , theView.bounds.size.height));
        [theView.layer renderInContext:context];
        UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return  theImage;
    }
}

//获得某个范围内的屏幕图像
+ (UIImage *)imageFromView:(UIView *)theView atFrame:(CGRect)r {
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    [theView.layer renderInContext:context];
    if ([theView isKindOfClass:[UIScrollView class]]) {
        UIScrollView *scrollview = (UIScrollView *)theView;
        UIGraphicsBeginImageContextWithOptions(scrollview.contentSize, NO, 4.0f);
    }else {
        UIGraphicsBeginImageContextWithOptions(theView.frame.size, NO, 4.0f);
    }
    CGContextSaveGState(context);
    if ([theView isKindOfClass:[UIScrollView class]]) {
        UIScrollView *scrollView = (UIScrollView *)theView;
        CGPoint savedContentOffset = scrollView.contentOffset;
        CGRect savedFrame = scrollView.frame;
        scrollView.contentOffset = CGPointZero;
        scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
        [scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
        scrollView.contentOffset = savedContentOffset;
        scrollView.frame = savedFrame;
    }
    UIRectClip(r);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return  theImage;
}

// 通过传入一张图片的名称,我还给你一张拉伸不变形的图片
+ (UIImage *)resizableImageName:(NSString *)imageName {
    // 加载图片
    UIImage *image = [UIImage imageNamed:imageName];
    // 拉伸图片不变形
    return [image stretchableImageWithLeftCapWidth:image.size.width * 0.5 topCapHeight:image.size.height * 0.5];
}
+ (UIImage *)resizableImage:(UIImage *)image {
    return [image stretchableImageWithLeftCapWidth:image.size.width * 0.5 topCapHeight:image.size.height * 0.5];
}

#pragma mark - 颜色转换成图片(带圆角的)
+ (UIImage *)imageWithColor:(UIColor *)color redius:(CGFloat)redius size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef ref = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(ref, color.CGColor);
    CGContextFillRect(ref, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIGraphicsBeginImageContext(image.size);
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, image.size.width, image.size.height) cornerRadius:redius];
    [path addClip];
    [image drawAtPoint:CGPointZero];
    UIImage *image1 = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image1;
}

#pragma mark - 根据视频地址生成缩略图
+ (UIImage*)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&thumbnailImageGenerationError];
    
    if (!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@", thumbnailImageGenerationError);
    
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef]: nil;
    
    return thumbnailImage;
}

+ (void)thumbnailImageForVideo:(NSURL *)videoURL withCompletionBlock:(ThumbnailBlock)block
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
        NSParameterAssert(asset);
        AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
        assetImageGenerator.appliesPreferredTrackTransform = YES;
        assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            CGImageRef thumbnailImageRef = NULL;
            CFTimeInterval thumbnailImageTime = 0;
            NSError *thumbnailImageGenerationError = nil;
            thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&thumbnailImageGenerationError];
            
            if (!thumbnailImageRef) {
                
                NSLog(@"thumbnailImageGenerationError %@", thumbnailImageGenerationError);
                
                if (block) {
                    block(NO, nil);
                }
                
            } else {
                UIImage *thumbnailImage = [[UIImage alloc] initWithCGImage:thumbnailImageRef];
                
                if (block) {
                    block(YES, thumbnailImage);
                }
            }
            
        });
    });
}

// 图片浏览器
+ (void)browseURLImages:(NSArray <YYPhotoGroupItem *>*)groupItems fromView:(UIView *)fromView {
    if (groupItems.count <= 0) {
        return;
    }
    YYPhotoGroupView *v = [[YYPhotoGroupView alloc] initWithGroupItems:groupItems];
    v.blurEffectBackground = NO;
    [v presentFromImageView:fromView toContainer:[UIApplication sharedApplication].keyWindow animated:YES completion:nil];
}




@end
